<template>
  <el-dialog title :visible.sync="openEditCakeFlag" :before-close="handleCakeClose" center :append-to-body="true"
    :lock-scroll="false" width="70%" z-index="2007">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="商品" name="first">
        <el-col style="margin-top: 1%">
          <div class="order-message d-f ai-c">
            <el-input class="w-400" v-model="cakeInput" clearable placeholder="请输入商品名称" size="small"></el-input>
            <div class="ml-15" v-if="!onlyEditParts">
              <XmCascader class="w-400" placeholder="请选择商品类型" separator=">" size="small" :props="{ multiple: true, value: 'id', label: 'categoryName' }" v-model="categoryIds" :options="cakeTypelist" clearable @change="handelCakeTypeChange"></XmCascader>
            </div>
            <div style="margin-left: 15px">
              <el-button icon="el-icon-search" type="primary" size="small" @click="searchCake()">查询</el-button>
            </div>
          </div>
          <el-scrollbar class="page-component__scroll" v-loading="Loading" style="width: 100%; height: 600px">
            <div v-for="(item, index) in list" :key="index" class="order-list">
              <div class="order-list-item">
                <div class="orderdetail-header-area">
                  <div class="order-header" style="display: flex; justify-content: space-between">
                    <div class="order-num">
                      <span>{{ item.name }}</span>
                      <i></i>
                    </div>
                    <div class="order-state"></div>
                    <el-tag type="danger" style="margin-right: 50%">{{
                        item.categoryName
                    }}</el-tag>
                  </div>
                </div>
                <div class="order-user-area" style="display: flex">
                  <div style="width: 100px; height: 80px; margin-right: 10px">
                    <img style="width: 100px; height: 80px" :src="item.mainPic" alt="" />
                  </div>
                  <div style="margin-left: 10px; width: 86%">
                    <div class="user-phone-address">
                      <div style="display: flex">
                        <el-col style="width: 75%">
                          <h3 style="
                                margin: 0 0 9px 0;
                                padding-bottom: 5px;
                                border-bottom: 1px solid #c0c4cc;
                                width: 70px;
                                text-align: center;
                              ">
                            规格
                          </h3>
                          <div v-for="(cakeing, key) in item.goodsSkuVOS" :key="key" style="margin-bottom: 5px">
                            <el-button @click="choiceCheck(cakeing, index, $event)">{{
                                cakeing.specs
                            }}</el-button>
                          </div>
                        </el-col>
                        <el-col style="width: 25%">
                          <h3 style="
                                margin: 0 0 9px 0;
                                padding-bottom: 5px;
                                border-bottom: 1px solid #c0c4cc;
                                width: 70px;
                                text-align: center;
                              ">
                            价格
                          </h3>
                          <div v-for="(cakeing, key) in item.goodsSkuVOS" :key="key"
                            style="line-height: 40px; margin-bottom: 5px">
                            <span style="
                                  display: inline-block;
                                  text-align: center;
                                "><i class="price-style" style="color: red; margin-right: 5px">{{ (cakeing.price /
                                    100).toFixed(2)
                                }}</i>元</span>
                          </div>
                        </el-col>
                      </div>
                      <el-button type="primary" @click="addEditCake(item)">添加</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <pagination v-show="shopTotal > 0" :total="shopTotal" :page.sync="productList.page"
              :limit.sync="productList.size" @pagination="getCakeList" />
          </el-scrollbar>
        </el-col>
      </el-tab-pane>
      <el-tab-pane label="备款蛋糕" name="second" v-if="!onlyEditParts">
        <el-col style="margin-top: 1%">
          <div class="order-message" style="width: 100%; height: 35px">
            <el-col :span="10">
              <el-input v-model="input" clearable placeholder="请输入蛋糕名称" size="small"></el-input>
            </el-col>
            <el-col :span="5" style="margin-left: 15px">
              <el-button icon="el-icon-search" type="primary" size="small" @click="searchProvisionsGoods()">查询
              </el-button>
            </el-col>
          </div>
          <el-scrollbar class="page-component__scroll" style="width: 100%; height: 600px">
            <div v-loading="Loading" v-for="(cakeMessage, index) in getGoodsPageList" :key="index" class="order-list">
              <div class="order-list-item">
                <div class="orderdetail-header-area" style="padding-top: 10px">
                  <div class="order-header">
                    <div class="order-num" style="width: fit-content">
                      <span>{{ cakeMessage.goodsName }}</span>
                      <!-- <i></i> -->
                    </div>
                    <div class="order-state"></div>
                  </div>
                </div>
                <div class="order-user-area" style="display: flex">
                  <div style="margin-left: 10px; width: 100%">
                    <div class="user-phone-address">
                      <div style="display: flex">
                        <el-col style="width: 65%">
                          <div class="phone-title">
                            蛋糕旧单号：<span style="color: #000">{{
                                cakeMessage.xmbzNo
                            }}</span>
                          </div>
                          <div class="phone-title">
                            蛋糕明细编码：<span style="color: #000">{{
                                cakeMessage.orderDetailId
                            }}</span>
                          </div>
                          <div class="phone-title">
                            规格：<span style="color: #000">{{
                                cakeMessage.goodsSpecs
                            }}</span>
                          </div>
                          <div style="
                                display: flex;
                                justify-content: space-between;
                              ">
                            <div class="phone-title">
                              价格：<i class="price-style c-red">{{
                                  (cakeMessage.cakePrice / 100).toFixed(2)
                              }}</i>
                            </div>
                            <div class="phone-title">
                              数量：<span style="color: #000">{{
                                  cakeMessage.cakeNum
                              }}</span>
                            </div>
                          </div>
                          <div style="
                                display: flex;
                                justify-content: space-between;
                              ">
                            <div class="phone-title">
                              城市：<span style="color: #000">{{
                                  cakeMessage.cityName
                              }}</span>
                            </div>
                            <div class="phone-title">
                              总仓：<span style="color: #000">{{
                                  cakeMessage.mainWarehouse
                              }}</span>
                            </div>
                            <div class="phone-title">
                              分仓：<span style="color: #000">{{
                                  cakeMessage.branchWarehouse
                              }}</span>
                            </div>
                          </div>
                        </el-col>
                      </div>
                      <div style="
                            display: flex;
                            justify-content: flex-end;
                            margin-right: 50px;
                          ">
                        <el-button type="primary" @click="choiceGoodsCheck(cakeMessage)">添加</el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <pagination v-show="GoodsPageTotal > 0" :total="GoodsPageTotal"
              :page.sync="getProvisionsGoodsPageQuery.page" :limit.sync="getProvisionsGoodsPageQuery.size"
              @pagination="getProvisionsGoodsPageList" />
          </el-scrollbar>
        </el-col>
      </el-tab-pane>
      <el-tab-pane label="已选商品" name="third">
        <el-col style="margin-top: 1%">
          <el-scrollbar class="page-component__scroll" style="height: 600px">
            <div>
              <table v-for="(value, index) in tableData" :key="index" class="order-list selected-table">
                <span v-if="value.workOrderProvisionsIds && value.workOrderProvisionsIds.length" style="position: absolute;right: 0;top: 0;width: 0;height: 0;border-top: 60px solid #CCC;border-left: 60px solid transparent;">
                  <i style="position: absolute;top: -55px;right: 15px;color: #fff;transform: rotate(-49deg);">备款</i>
                </span>
                <tr>
                  <td>商品名称</td>
                  <td>商品规格</td>
                  <td>价格</td>
                  <td>现价</td>
                  <td>商品数量</td>
                  <td>是否赠品</td>
                </tr>
                <tr>
                  <td style="width: 8rem">{{ value.goodsName }}</td>
                  <td style="width: 6rem">{{ value.specs }}</td>
                  <td style="width: 4rem">
                    {{ (value.originalPrice / 100).toFixed(2) }}
                  </td>
                  <td style="width: 4rem">
                    {{ (value.totalPrice / 100).toFixed(2) }}
                  </td>
                  <td class="d-if ta-c w-300">
                    <el-button
                      v-show="canItemEditNum(value)"
                      size="mini"
                      @click="handleAddNum(value)"
                    >添加</el-button>

                    <el-input
                      v-model.number="value.num"
                      class="mlr-10"
                      @input="changeInputNum(index, $event)"
                      min = '1'
                      clearable
                      :disabled="!canItemEditNum(value)"
                      type="text"></el-input>

                    <el-button
                      v-show="canItemEditNum(value)"
                      size="mini"
                      type="danger"
                      @click="handleReduceNum(value)"
                    >减少</el-button>
                  </td>
                  <td>
                    <XmSelect class="w-100" v-model="value.gift" :options="giftTypeList" @change="handleGiftChange(value)"></XmSelect>
                  </td>
                </tr>
                <tr>
                  <td colspan="4">
                    <p style="color: red; font-size: 15px; font-weight: 600">
                      祝福语
                    </p>
                    <el-input v-model.trim="value.blessings" maxlength="32" type="textarea" placeholder="请输入祝福语"
                      class="orderspecial" show-word-limit autosize :readonly="!canEditGoods(value)"></el-input>
                  </td>
                  <td style="color: red; font-size: 15px; font-weight: 600">
                    <div style="
                          display: flex;
                          justify-content: space-around;
                          line-height: 2;
                        ">
                      总价：<span id="singletonPrice">{{
                          (value.totalPrice * value.num / 100).toFixed(2)
                      }}</span>
                      <el-button size="small" @click="cleanOrder(index, $event)" v-if="canEditGoods(value)">清除</el-button>
                    </div>
                  </td>
                </tr>
              </table>
              <div style="
                    display: flex;
                    flex-direction: column;
                    align-items: flex-end;
                  ">
                <p style="
                      color: red;
                      font-size: 20px;
                      font-weight: 700;
                      margin-right: 20px;
                    ">
                  所选商品总价：{{ (getSumPrice() / 100).toFixed(2) }}
                </p>
              </div>
              <el-col style="
                    display: flex;
                    flex-direction: column;
                    align-items: flex-end;
                  ">
                <el-button type="primary" @click="onAddSumbit()" style="margin-right: 20px">提交</el-button>
              </el-col>
            </div>
          </el-scrollbar>
        </el-col>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import {
  getCategories,
} from "@/api/pending";
import {
  getProvisionsGoodsPage, // 备款商品分页列表
  shopList, // 蛋糕商品列表
  judgeGoodsClose, // 判断当前商品是否关闭
} from "@/api/createOrder";
import Pagination from "@/components/Pagination"; // 分页
export default {
  components: {
    Pagination
  },
  props: {
    ruleForm: {
      type: Object,
      default: () => { }
    },
    onlyEditParts: {
      type: Boolean,
      default: false
    },
    canEditNum: {
      type: Boolean,
      default: false
    },
    isReserveId: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      openEditCakeFlag: false,
      tableData: [],
      activeName: 'first',
      sumPrice: 0,
      Loading: false,
      shopTotal: 0,
      GoodsPageTotal: 0,
      getProvisionsGoodsPageQuery: {
        // 备款商品分页列表(请求)
        goodsName: "",
        page: 1,
        size: 10,
        cityId: "", //组织架构ID
      },
      productList: {
        page: 1,
        size: 10,
      },
      input: "", // 备款蛋糕
      cakeInput: '',
      list: [],
      cakelist: "", // 点击添加蛋糕前，将点击的规格的数据传给cakelist
      judgeGoodsCloseQuery: {
        // 判断当前商品是否关闭请求
        warehouseId: "", // 仓库id
        skuCode: "", // sku码
      },
      getGoodsPageList: "", // 备款商品分页列表
      partsTypeId: '',
      giftTypeList: [{
        label: '非赠品',
        value: '0',
      },{
        label: '赠品',
        value: '1',
      }],
      cakeTypelist: [],
      categoryIds: [],
    };
  },
  methods: {
    show(options) {
      this.openEditCakeFlag = true
      this.initData(options)
    },
    initData({ shoplist }) {
      this.tableData = JSON.parse(JSON.stringify(shoplist));
      this.tableData.forEach((item) => {
        item.price = item.totalPrice;
        item.specs = item.goodsSpecs;
        item.gift = item.gift !== undefined ? item.gift + '' : undefined
      });
      this.activeName = "first"; // 编辑蛋糕打开即“商品”
      this.getCakeList();
    },
    handleCakeClose() {
      // 关闭蛋糕弹窗
      this.$confirm("确认关闭？")
        .then(() => {
          this.openEditCakeFlag = false
        })
        .catch(() => { });
    },
    searchCake() {
      this.productList.page = 1
      this.getCakeList()
    },
    // 普通蛋糕分页列表
    getCakeList() {
      this.Loading = true;
      if (this.ruleForm.deptId !== "") {
        this.openEditCakeFlag = true;
        shopList(this.getParams()).then((res) => {
          this.shopTotal = res.data.data.total;
          this.list = res.data.data.rows;
        });
      } else {
        this.$message({
          message: "您还未选择城市，请选择城市后再添加蛋糕",
          type: "warning",
        });
      }
      setTimeout(() => {
        this.Loading = false;
      }, 1.5 * 1000);
    },
    getParams() {
      const parentCategoryIds = this.cakeTypelist.map(item => item.id)
      const params = {
        ...this.productList,
        deptId: this.ruleForm.deptId,
        name: this.cakeInput,
        parentCategoryId: this.onlyEditParts ? this.partsTypeId : undefined,
        categoryIds: (this.categoryIds && this.categoryIds.length) ? this.categoryIds.map(item => {
          return item[item.length - 1]
        }).join(',') : undefined,
      }
      return params
    },
    // 蛋糕规格（型号）选择
    choiceCheck(cakeing, index, e) {
      cakeing = JSON.stringify(cakeing);
      cakeing = JSON.parse(cakeing);
      this.cakelist = cakeing;
      this.skuId = e.currentTarget.dataset.id;
    },
    // 添加蛋糕
    addEditCake(item) {
      this.judgeGoodsCloseQuery.warehouseId = this.ruleForm.warehouseId;
      if (item.id == this.cakelist.goodsId) {
        const cakeInfo = {
          ...this.cakelist,
          id: this.isReserveId ? this.cakelist.id : '',
          skuId: this.cakelist.id,
          goodsSpecs: this.cakelist.specs,// 尺寸
          originalPrice: this.cakelist.price,
          totalPrice: this.cakelist.price,
          goodsTypeName: this.cakelist.categoryName,
          workOrderProvisionsDTOList: [],
          workOrderProvisionsIds: [],
          num: 1,
          productionState: 1,
          productionStateName: "未确认",
          gift: '0',
        }
        this.judgeGoodsCloseQuery.skuCode = this.cakelist.skuCode;
        judgeGoodsClose(this.judgeGoodsCloseQuery).then((res) => {
          if (res.data.code == 200) {
            if (res.data.data == true) {
              this.$message({
                showClose: true,
                message: "添加蛋糕失败，所选仓库没有生产该蛋糕的原料。",
                type: "warning",
              });
            } else if (res.data.data == false) {
              this.$message({
                showClose: true,
                message: "添加蛋糕成功",
                type: "success",
              });
              this.tableData.push(cakeInfo);
              this.tableData = JSON.stringify(this.tableData);
              this.tableData = JSON.parse(this.tableData);
            }
            this.cakelist = "";
          }
        });
      }
    },
    searchProvisionsGoods() {
      this.getProvisionsGoodsPageQuery.page = 1
      this.getProvisionsGoodsPageList()
    },
    //备款商品分页列表(查询)
    getProvisionsGoodsPageList() {
      this.Loading = true;
      this.getProvisionsGoodsPageQuery.cityId = this.ruleForm.deptId;
      this.getProvisionsGoodsPageQuery.goodsName = this.input;
      getProvisionsGoodsPage(this.getProvisionsGoodsPageQuery).then((res) => {
        this.GoodsPageTotal = res.data.data.total;
        this.getGoodsPageList = res.data.data.rows || [];
      });
      setTimeout(() => {
        this.Loading = false;
      }, 0.5 * 1000);
    },
    handleClick(tab) {
      if (tab.label == "商品") {
        this.getCakeList(); // 普通蛋糕分页列表
      } else if (tab.label == "备款蛋糕") {
        this.getProvisionsGoodsPageList(); // 备款商品分页列表
      }
    },
    // 备款蛋糕规格（型号）选择
    choiceGoodsCheck(cakeMessage) {
      let provisionsIds = [];
      this.tableData.forEach((cakeitem) => {
        provisionsIds = provisionsIds.concat(cakeitem.workOrderProvisionsIds ? cakeitem.workOrderProvisionsIds : [])
      });
      if (provisionsIds.indexOf(cakeMessage.id) == -1) {
        const cakeInfo = {
          ...cakeMessage,
          id: this.isReserveId ? cakeMessage.id : '',
          skuId: cakeMessage.id,
          specs: cakeMessage.goodsSpecs,// 尺寸
          price: cakeMessage.cakePrice,
          originalPrice: cakeMessage.cakePrice,
          totalPrice: cakeMessage.cakePrice,
          orderId: cakeMessage.orderId,
          goodsTypeName: cakeMessage.categoryName,
          workOrderProvisionsDTOList: [],
          workOrderProvisionsType: '备款',
          workOrderProvisionsIds: [cakeMessage.id],
          num: cakeMessage.cakeNum,
          productionState: 4,
          productionStateName: "已入库",
          gift: '0',
        }
        this.$message({
          showClose: true,
          message: "添加蛋糕成功",
          type: "success",
        });
        this.tableData.push(cakeInfo);
      } else {
        this.$message({
          message: "此蛋糕已经添加过，请不要重复添加",
          type: "warning",
        });
      }
    },
    // 蛋糕提交
    onAddSumbit() {
      const sumPrice = this.getSumPrice()
      this.openEditCakeFlag = false;
      this.$emit('onGoodsSubmit', { shoplist: this.tableData, sumPrice: sumPrice })
    },
    // 删除单个订单
    cleanOrder(index, e) {
      this.$delete(this.tableData, index);
    },
    getSumPrice() {
      let sumPrice = 0;
      this.tableData.forEach((value, index) => {
        sumPrice += value.totalPrice * value.num;
      });
      return sumPrice
    },
    canEditGoods(goods) {
      return this.onlyEditParts ? goods.goodsTypeName == '配件' : true
    },
    getCategories() {
      return getCategories().then(res => {
        this.cakeTypelist = res.data.data || []
      })
    },
    keyupEnter(event) {
      if (event.keyCode == 13) {
        if (this.activeName == 'first') {
          this.searchCake()
        } else if (this.activeName == 'second') {
          this.searchProvisionsGoods()
        }
      }
    },
    canItemEditNum (value) {
      // 不是备款蛋糕才能加
      return this.canEditNum && !(value.workOrderProvisionsIds && value.workOrderProvisionsIds.length)
    },
    handleAddNum(value) {
      value.num++
    },
    handleReduceNum(value) {
      if(value.num > 1) {
        value.num --
      }
    },
    // 是否赠品
    handleGiftChange(value) {
      if (value.gift == 1) {
        value.totalPrice = 0
      } else if (value.gift == 0) {
        value.totalPrice = value.originalPrice
      }
    },
    handelCakeTypeChange() {
      console.log(this.categoryIds)
    },
  },
  watch: {
    openEditCakeFlag(next) {
      if (next) {
        window.addEventListener("keydown", this.keyupEnter);
      } else {
        window.removeEventListener("keydown", this.keyupEnter);
      }
    }
  },
  created() {
    this.getCategories().then(() => {
      const partsType = this.cakeTypelist.find(item => item.categoryName == '配件')
      this.partsTypeId = partsType.id
    })
  }
};
</script>
<style lang="scss" scoped>
.order-list {
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  font-family: Helvetica Neue, Arial, PingFang SC, microsoft yahei, STXihei;
  color: #3f4156;
  box-sizing: inherit;
  margin-top: 10px;
  margin: 0.5rem;
  box-shadow: rgb(223, 228, 237) 2px 2px 10px;
  .order-list-item {
    font-size: 14px;
    font-weight: 400;
    line-height: 1.5;
    font-family: Helvetica Neue, Arial, PingFang SC, microsoft yahei, STXihei;
    color: #3f4156;
    box-sizing: inherit;
    margin-bottom: 20px;
    border-bottom: 1px solid #fff;
    background: #fff;
    .orderdetail-header-area {
      .order-header {
        position: relative;
        // height: 50px;
        overflow: hidden;
        padding-top: 10px;
        .order-num {
          margin-right: 20px;
          display: inline-block;
          position: relative;
          // height: 33px;
          background: #585a6e;
          color: #fff;
          padding: 0 10px;
          text-align: left;
          display: flex;
          align-items: center;
          span {
            position: relative;
            z-index: 9;
            font-size: 16px;
            // line-height: 2;
          }
          // margin-top: 10px;
        }
      }
    }
    .order-user-area {
      padding: 10px 20px;
    }
  }
}
.selected-table {
  position: relative;
  border-collapse: collapse;
  text-align: center;
  margin-bottom: 20px;
  width: 98%;
  tr {
    border: 1px solid rgb(223, 228, 237);
    td {
      border: 1px solid rgb(223, 228, 237);
      padding: 0.5rem 0.5rem;
      height: 2.6rem;
      line-height: 1rem;
    }
  }
}
</style>